package com.bz.common;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.MDC;

public class LogUtils {

    /**
     * 请求调用链(从header中获取)
     */
    public static final String HEADER_REQUEST_ID = "requestId";

    /**
     * MDC调用链log中的日志标识
     */
    public static final String MDC_REQUEST_ID    = "requestId";

    public static void error(Logger log, Throwable t, String msg) {
        log.error(msg, t);
    }

    public static void info(Logger log, String msg) {
        log.info(msg);
    }

    public static void warn(Logger log, String msg) {
        log.warn(msg);
    }

    public static void removeMdc() {
        // 调用结束后删除
        Set<String> mscset = new HashSet<>();
        mscset.add("requestId");
        for (String m : mscset) {
            MDC.remove(m);
        }
    }

    public static void addMdc(HttpServletRequest request, HttpServletResponse response) {

        String requestId = request.getHeader(LogUtils.HEADER_REQUEST_ID);
        String host = request.getRemoteHost();
        String uri = request.getRequestURI();

        String targethost = request.getRemoteHost();
        String targeturi = request.getRemoteAddr();

        String param = request.getQueryString();
        String resopnseBody = "";
        String duraion = "";

        Map<String, String> mdcmap = new HashMap<>();
        mdcmap.put("requestId", requestId);
        mdcmap.put("host", host);
        mdcmap.put("uri", uri);
        mdcmap.put("targethost", targethost);
        mdcmap.put("targeturi", targeturi);

        mdcmap.put("param", param);
        mdcmap.put("resopnseBody", resopnseBody);
        mdcmap.put("duraion", duraion);

        for (Entry<String, String> m : mdcmap.entrySet()) {
            if (null != m.getValue()) {
                MDC.put(m.getKey(), m.getValue());
            }
        }

    }

    public static void addMdc(String requestId) {
        Map<String, String> mdcmap = new HashMap<>();
        mdcmap.put("requestId", requestId);
        for (Entry<String, String> m : mdcmap.entrySet()) {
            MDC.put(m.getKey(), m.getValue());
        }
    }

}
